<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>title</title>
    <script src="https://cdn.staticfile.net/jquery/1.10.2/jquery.min.js"></script>
    <script src="/js/env.js"></script>
    <script>
        $(function () {
            let socket;
            let messageObjList = [];
            let userList = [];
            $("#loginUser").text("欢迎你，" + localStorage.getItem("username"))

            function onopen() {
                console.log("建立链接")
            }

            function onclose() {
                console.log("关闭链接")
            }

            async function selectItem(item) {
                console.log($(".header"))
                $(".header").text("正在和 " + item + " 聊天")
                await localStorage.setItem("toUser", item)
                console.log("选中" + item)
                await getMessageList()
            }

            async function getMessageList() {
                const res = await $.ajax({
                    url: `/list?fromUser=${localStorage.getItem("username")}&toUser=${localStorage.getItem("toUser")}`,
                    type: "GET",
                })
                console.log(res)
                if (res.code === 200) {
                    messageObjList = res.data
                }
                refreshMessageList()
            }

            function onmessage({data}) {
                const res = JSON.parse(data)
                if (res.type === "open" || res.type === "close") {
                    let arr = res.data
                    userList = arr.filter(item => item !== localStorage.getItem("username"))
                    refreshUserList()
                } else {
                    let messageObj = res.data
                    messageObjList.push(messageObj)
                    refreshMessageList()
                }
            }

            function initWebsocket() {
                const username = localStorage.getItem("username")
                socket = new WebSocket(`${wsBaseUrl}/chat/` + username)
                socket.onopen = onopen
                socket.onclose = onclose
                socket.onmessage = onmessage
            }

            initWebsocket()

            $("#sendMessage").click(function () {
                const message = $("#inputText").val()
                const messageObj = {
                    fromUser: localStorage.getItem("username"),
                    toUser: localStorage.getItem("toUser"),
                    message
                }
                socket.send(JSON.stringify(messageObj))
                messageObjList.push(messageObj)
                $("#inputText").val("")
                refreshMessageList()
            })

            function refreshUserList() {
                const arr = []
                $(".onlinePerson").empty()
                for (let item of userList) {
                    const pNode = document.createElement("p")
                    const pText = document.createTextNode(item)
                    pNode.appendChild(pText)
                    pNode.style.padding = "5px"
                    pNode.style.borderBottom = "1px solid black"
                    pNode.style.cursor = "pointer"
                    pNode.onclick = function () {
                        selectItem(item)
                    }
                    arr.push(pNode)
                }
                $(".onlinePerson").append(arr)
            }

            function refreshMessageList() {
                $(".content").empty()
                const arr = []
                for (let item of messageObjList) {
                    const pNode = document.createElement("p")
                    const pText = document.createTextNode(item.message)
                    pNode.appendChild(pText)
                    pNode.style.paddingLeft = "10px"
                    pNode.style.paddingRight = "10px"
                    if (item.fromUser === localStorage.getItem("username")) {
                        pNode.style.textAlign = "right"
                    } else {
                        pNode.style.textAlign = "left"
                    }
                    arr.push(pNode)
                }
                $(".content").append(arr)
                scrollToBottom()
            }

            function scrollToBottom() {
                const myDiv = $(".content")
                myDiv.scrollTop(myDiv.prop("scrollHeight"))
            }
        })
    </script>
</head>
<body>

<div class="container"
     style="height: 500px;width: 800px;background-color: aquamarine;position:absolute;left: 50%;top:50%;transform: translate(-50%,-50%)">
    <h3 id="loginUser" style="text-align: center"></h3>
    <div class="box" style="display: flex;justify-content: space-between;height: 100%">
        <div class="left" style="background-color: greenyellow;width: 20%;height: 90%">
            <h3 style="text-align: center">在线用户</h3>
            <div class="onlinePerson" style="width: 100%;height: 100%;text-align: center">
            </div>
        </div>
        <div class="right" style="background-color: antiquewhite;width: 80%;height: 90%">
            <div class="header" style="padding-left: 10px;height: 10%;background-color: sandybrown"></div>
            <div class="content" style="overflow: auto;height: 80%">

            </div>
            <div class="input"
                 style="height: 10%;background-color: beige;display: flex;justify-content: space-between;align-items: center">
                <textarea name="" id="inputText" cols="80" rows="2"></textarea>
                <button id="sendMessage" style="margin-right: 20px;cursor: pointer">发送</button>
            </div>
        </div>
    </div>
</div>
</body>
</html>